<template>
  <div>
    <div class="form-edit-btns">
      <el-button type="primary" size="mini" icon="el-icon-plus"
                 @click="showAddView">
        添加
      </el-button>
    </div>
    <el-main style="padding-left: 0px;padding-top: 0px">
      <div class="table-box">
        <el-table
          :data="objs"
          v-loading="tableLoading"
          border
          stripe
          @selection-change="handleSelectionChange"
          size="mini"
          style="width: 100%">
          <el-table-column
            type="selection"
            align="left"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="题目"
          >
          </el-table-column>

          <el-table-column
            prop="quizCategory.name"
            label="类型"
          >
          </el-table-column>



          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button @click="showEditView(scope.row)" type="text"
                         size="mini">编辑
              </el-button>
              <el-button type="text" size="mini"
                         @click="deleteObj(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          :page-size="10"
          :current-page="currentPage"
          @current-change="currentChange"
          layout="prev, pager, next"
          :total="totalCount">
        </el-pagination>
        <div class="form-edit-btns" style="float:right">
          <el-button type="danger" size="mini" v-if="objs.length>0" :disabled="multipleSelection.length==0"
                     @click="deleteMany">批量删除
          </el-button>
        </div>
      </div>
    </el-main>

    <el-form :model="obj" :rules="rules" ref="addForm" style="margin: 0px;padding: 0px;">
      <div style="text-align: left">
        <el-dialog
          :title="dialogTitle"
          style="padding: 0px;"
          :close-on-click-modal="false"
          :visible.sync="dialogVisible"
          width="77%">

            <el-form-item label="题目:" prop="content" label-width="100px">
              <el-input prefix-icon="el-icon-edit" v-model="obj.content" size="mini"
                        type="textarea"
                        placeholder="请输入题目"></el-input>
            </el-form-item>


            <el-form-item label="类型:" prop="quiz_category_id" label-width="100px">
              <el-select @change="categoryChange" v-model="obj.quiz_category_id" placeholder="请选择">
                <el-option
                  v-for="item in quiz_category_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>


          <el-form-item v-bind:key="c" v-for="c in option_num" :label="'选项'+c+':'" prop="option" label-width="100px">
            <el-input  v-model="option_list[c]" size="mini"
                      type="textarea"
                      placeholder="请输入选项">

            </el-input>


          </el-form-item>


          <el-form-item label="答案:" prop="correct_answer" label-width="100px">
            <el-input prefix-icon="el-icon-edit" v-model="obj.correct_answer" size="mini"
                      placeholder="请输入答案选项，例如1，2。多个选项用逗号隔开"></el-input>
          </el-form-item>





          <span slot="footer" class="dialog-footer">
    <el-button size="mini" @click="cancelEidt">取 消</el-button>
    <el-button size="mini" type="primary" @click="add('addForm')">确 定</el-button>
  </span>
        </el-dialog>
      </div>
    </el-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        objs: [],
        dialogTitle: '',
        multipleSelection: [],
        totalCount: -1,
        currentPage: 1,
        dialogVisible: false,
        tableLoading: false,
        quiz_category_list:[],
        option_num:0,
        option_list:[],
        // result_num:0,
        obj: {
          content: '',
          quiz_category_id:'',
          option_list:'',
          correct_answer:''
        },
        rules: {
          content: [{required: true, message: '必填:题目', trigger: 'blur'}],
          quiz_category_id: [{required: true, message: '必填:试题类型', trigger: 'blur'}]
        }
      };
    },
    mounted: function () {
      this.loadObjs();
      this.loadCategoryList();
    },
    methods: {


      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      deleteMany(){
        this.$confirm('此操作将删除[' + this.multipleSelection.length + ']条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var ids = '';
          for (var i = 0; i < this.multipleSelection.length; i++) {
            ids += this.multipleSelection[i].id + ",";
          }
          this.doDelete(ids);
        }).catch(() => {
        });
      },
      deleteObj(row){
        this.$confirm('此操作将永久删除[' + row.content + '], 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doDelete(row.id);
        }).catch(() => {
        });
      },
      doDelete(ids){
        this.tableLoading = true;
        var _this = this;
        this.deleteRequest("/quiz/delete/" + ids).then(resp=> {
          _this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.$message({type: data.status, message: data.msg});
            _this.loadObjs();
          }
        })
      },


      currentChange(currentChange){
        this.currentPage = currentChange;
        this.loadObjs();
      },
      loadObjs(){
        var _this = this;
        this.tableLoading = true;
        this.getRequest("/quiz/list?page=" + this.currentPage + "&size=10&type=选择题").then(resp=> {
          this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.objs = data.data.arrays;
            _this.totalCount = data.data.count;
          }
        })
      },

      categoryChange() {

        var quiz_list = this.quiz_category_list.filter(i=>i.id==this.obj.quiz_category_id)
        //console.log(quiz_list[0]);
        this.option_num = quiz_list[0].option_num;
        // this.result_num = quiz_list[0].correct_answer_num;

      },

      loadCategoryList(){
        var _this = this;
        this.tableLoading = true;
        this.getRequest("/quiz/category/list?type=选择题").then(resp=> {
          this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.quiz_category_list = data.data.arrays;
          }
        })
      },



      add(formName){
        var _this = this;

        var m = {};
        for (let index in this.option_list) {
          m[index+""] = this.option_list[index];
        }

        this.obj.option_list = JSON.stringify(m);

        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.obj.id) {
              //更新
              this.tableLoading = true;
              this.postRequest("/quiz/update", this.obj).then(resp=> {
                _this.tableLoading = false;
                if (resp && resp.status == 200) {
                  var data = resp.data;
                  _this.$message({type: data.status, message: data.msg});
                  _this.dialogVisible = false;
                  _this.emptyObjData();
                  _this.loadObjs();
                }
              })
            } else {
              //添加


              this.tableLoading = true;
              this.postRequest("/quiz/add", this.obj).then(resp=> {
                _this.tableLoading = false;
                if (resp && resp.status == 200) {
                  var data = resp.data;
                  _this.$message({type: data.status, message: data.msg});
                  _this.dialogVisible = false;
                  _this.emptyObjData();
                  _this.loadObjs();
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      cancelEidt(){
        this.dialogVisible = false;
        this.emptyObjData();
      },
      showEditView(row){
        //console.log(row)
        this.dialogTitle = "编辑试题";
        this.obj.content = row.content;
        this.obj.id = row.id;
        this.obj.quiz_category_id = row.quizCategory.id;
        this.option_num = row.quizCategory.option_num;
        this.option_list = [undefined];
        var m = JSON.parse(row.option_list);
        for (let index=1;index<=this.option_num;index++) {
          this.option_list.push(m[index]);
        }
        this.obj.correct_answer = row.correct_answer;

        this.dialogVisible = true;
      },
      showAddView(){
        this.dialogTitle = "添加试题";
        this.dialogVisible = true;
        var _this = this;
      },
      emptyObjData(){
        this.obj = {
          content: '',
          quiz_category_id:'',
          option_list:''
        }
        this.option_num = 0;
        this.option_list = [];
      }
    }
  };
</script>
<style scoped>
  .el-dialog__body {
    padding-top: 0px;
    padding-bottom: 0px;
  }

  .slide-fade-enter-active {
    transition: all .8s ease;
  }

  .slide-fade-leave-active {
    transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }

  .slide-fade-enter, .slide-fade-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }
</style>
